//数据源管理
import React, { useState, useEffect }  from 'react';
import {Table, Row,Col, Modal, Button, Form, Input, message, List, Avatar} from 'antd';
import { getDataSources,saveDS,delDS ,testConnection} from "../api/metaDatasourceService";


export  default  function DataSource(props) {
    const [data, setData] = useState([]);
    const [visible, setVisible] = useState(false);
    const [selectedIds, setSelectedIds] = useState([]);//选择的数据源条目
    const [currentItemGuid,setCurrentItemGuid]=useState("");
    const [currentItemName,setCurrentItemName]=useState("");
    const [currentItemDriver,setCurrentItemDriver]=useState("");
    const [currentItemUrl,setCurrentItemUrl]=useState("");
    const [currentItemUserName,setCurrentItemUserName]=useState("");
    const [currentItemPassword,setCurrentItemPassword]=useState("");

    const [flag,setFlag]=useState(0);



        useEffect(() => {
            getDataSources().then(
                (res) => {
                     setData(res.data)
                },
                (error) => {
                    console.log("get UserList failed!");
                }
            );
        }, [flag]);

    const columns = [
        {
            title: '数据源名称',
            dataIndex: 'name',
            key: 'name',
        }
    ];
//取消
    const cancelModal=()=>{

        setVisible(false)

    }
    // const onOk=()=>{
    //     setVisible(false)
    // }


    const  add=()=>{
        setCurrentItemGuid("");
        setCurrentItemName("");
        setCurrentItemDriver("");
        setCurrentItemUrl("");
        setCurrentItemUserName("");
        setCurrentItemPassword("");

        form.setFieldsValue({"guid":"","driverclass":"","name":"","url":"","username":"","password":""});
        setVisible(true)
    }

    const  edit=()=>{
        let _ids = selectedIds;
        if (_ids.length > 1) {
            message.info("只能选择一个条目")
            return;
        }
        if (_ids.length < 1) {
            message.info("必须选择一个条目")
            return;
        }

        let _o=data.find( t=> t.guid==_ids[0])
        if(_o!=null){
            setCurrentItemGuid(_o.guid);
            setCurrentItemName(_o.name);
            setCurrentItemDriver(_o.driverclass);
            setCurrentItemUrl(_o.url);
            setCurrentItemUserName(_o.username);
            setCurrentItemPassword(_o.password);
            form.setFieldsValue({"guid":_o.guid,"driverclass":_o.driverclass,"name":_o.name,"url":_o.url,"username":_o.username,"password":_o.password});
        }
        setVisible(true)
    }

    const  del=()=>{
        let _ids = selectedIds;
        if (_ids.length > 1) {
            message.info("只能选择一个条目")
            return;
        }
        if (_ids.length < 1) {
            message.info("必须选择一个条目")
            return;
        }
        let  _obj={
            "guid": _ids[0],
        }
        delDS(_obj).then(
            (res) => {
                setFlag(flag+1);
                message.success("操作成功")
            },
            (error) => {
                message.success("操作失败")
            }
        );


    }

    const viewTables=()=>{
        let _ids = selectedIds;
        if (_ids.length > 1) {
            message.info("只能选择一个条目")
            return;
        }
        if (_ids.length < 1) {
            message.info("必须选择一个条目")
            return;
        }
        let  _obj={
            "guid": _ids[0],
        }
        delDS(_obj).then(
            (res) => {
                setFlag(flag+1);
                message.success("操作成功")
            },
            (error) => {
                message.success("操作失败")
            }
        );


    }


    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log("^^^^^^^^^^^^^^^^^^^^^^")
            console.log(selectedRowKeys)
            setSelectedIds( selectedRowKeys);




        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [form] = Form.useForm();

    //设置表单
    const setFormFields=()=>{
        form.setFieldsValue("guid",)
        form.setFieldsValue("driverclass",)
        form.setFieldsValue("name",)
        form.setFieldsValue("url",)
        form.setFieldsValue("username",)
        form.setFieldsValue("password",)
    }

    const getDataSource=(prop)=>{



        const onFinish = (values) => {
            console.log('Success:', values);
            let _obj={
                "driverclass": values.driverclass,
                "guid": values.guid,
                "name": values.name,
                "password": values.password,
                "url": values.url,
                "username": values.username
            }
            saveDS(_obj).then(
                (res) => {
                    //把后端数据组织到前端
                   // this.refreshForm(this.state.selectedFolderId);
                    setFlag(flag+1);
                    message.success("保存成功")
                    // 刷缓存;
                    setVisible(false);
                },
                (error) => {
                    //this.componentDidMount();
                    message.success("保存失败")
                }
            );



        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };

        const onCancelSelf=()=>{
            prop.cancelModal()
        }

        //获取连接
        const test_Connection=()=>{
            let _driverclass=form.getFieldValue("driverclass");
            let _url=form.getFieldValue("url");
            let _userName=form.getFieldValue("username");
            let _password=form.getFieldValue("password");
            let _obj={
                "driverclass":_driverclass,
                "password": _password,
                "url":_url,
                "username": _userName
            }

            testConnection(_obj).then(
                (res) => {
                    if(res.code==200){
                        message.success("连接成功")
                    }else{
                        message.warn("连接失败！")
                    }

                },
                (error) => {
                }
            );
        }




        return (
            <Form
                name="basic"
                form={form}
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    guid:currentItemGuid,
                    name: currentItemName,
                    driverclass: currentItemDriver,
                    url: currentItemUrl,
                    username: currentItemUserName,
                    password: currentItemPassword
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >

                <Form.Item
                     name="guid"
                    rules={[{
                        required: false,
                    }]}
                    hidden={true}
                >
                    <Input/>
                </Form.Item>


                <Form.Item
                    label="Name："
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: 'Please input name!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="driverclass"
                    name="driverclass"
                    rules={[
                        {
                            required: true,
                            message: 'Please input your driverclass!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>




                <Form.Item
                    label="url"
                    name="url"
                    rules={[
                        {
                            required: true,
                            message: 'Please input your url!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>



                <Form.Item
                    label="username"
                    name="username"
                    rules={[
                        {
                            required: true,
                            message: 'Please input your username!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>



                <Form.Item
                    label="password"
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: 'Please input your password!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>



                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>
                    <Button htmlType="button" onClick={onCancelSelf}>
                        Cancel
                    </Button>
                    <Button htmlType="button" onClick={test_Connection}>
                        testConnection
                    </Button>


                </Form.Item>
            </Form>
        );
    }


    const tableColumns = [
        {
            title: '表名',
            dataIndex: 'tablename',
            key: 'tablename',
        },
        {
            title: '说明',
            dataIndex: 'age',
            key: 'age',
        }
    ];


    const tableData = [
        {
            key: '1',
            name: 'John Brown',
            age: 32,
            address: 'New York No. 1 Lake Park',
            tags: ['nice', 'developer'],
        },
        {
            key: '2',
            name: 'Jim Green',
            age: 42,
            address: 'London No. 1 Lake Park',
            tags: ['loser'],
        },
        {
            key: '3',
            name: 'Joe Black',
            age: 32,
            address: 'Sidney No. 1 Lake Park',
            tags: ['cool', 'teacher'],
        },
    ];


    return (
        <>
            <Row>
            <Col span={8}>

            <Row>
                <Button onClick={add}>增加</Button>
                <Button onClick={edit}>修改</Button>
                <Button onClick={del}>删除</Button>
                <Button onClick={viewTables}>查看表</Button>
            </Row>


            <Row>


        <Table columns={columns}
               rowSelection={{
                   type: 'checkbox',
                   ...rowSelection,
               }}
                style={{width:"100%"}}
               dataSource={data} />
            </Row>

            </Col>

            <Col span={8}>
                <Row><h1>Table Info</h1></Row>

                <Row>
                    <Table columns={tableColumns} dataSource={tableData} />
                </Row>



            </Col>

            <Col span={8}>
                <Row><h1>Column Info</h1></Row>

                <Row>





                </Row>



            </Col>
            </Row>
            <Modal
                width={740}
                title="管理数据源"
                visible={visible}
                maskClosable={false}
                //confirmLoading={this.props.confirmLoading}
                // onOk={onOk}
                // okText='保存'
                // cancelText='返回'
                 onCancel={cancelModal}
                footer={null}
                getContainer={false}
                destroyOnClose
            >
                {getDataSource({cancelModal})}
            </Modal>
    </>


);
}



